'use client';

import Link from 'next/link';
import { usePathname, useSearchParams } from 'next/navigation';

interface PaginationProps {
  currentPage: number;
  totalPages: number;
  baseUrl?: string;
  onPageChange?: (page: number) => void;
}

export default function Pagination({ 
  currentPage, 
  totalPages, 
  baseUrl,
  onPageChange 
}: PaginationProps) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  
  // 如果只有一页，不显示分页
  if (totalPages <= 1) {
    return null;
  }

  // 构建分页链接
  const createPageLink = (page: number) => {
    const params = new URLSearchParams(searchParams.toString());
    params.set('page', page.toString());
    return baseUrl ? `${baseUrl}?${params.toString()}` : `${pathname}?${params.toString()}`;
  };
  
  // 处理页面点击
  const handlePageClick = (page: number, event: React.MouseEvent) => {
    if (onPageChange) {
      event.preventDefault();
      onPageChange(page);
    }
  };

  // 计算要显示的页码范围
  const renderPageButtons = () => {
    const pageButtons = [];
    
    // 始终显示首页按钮
    pageButtons.push(
      <li key="first">
        {currentPage === 1 ? (
          <span className="px-4 py-2 bg-red-600 text-white rounded-md cursor-default">
            1
          </span>
        ) : (
          <Link
            href={createPageLink(1)}
            onClick={(e) => handlePageClick(1, e)}
            className="px-4 py-2 bg-gray-800 hover:bg-gray-700 text-white rounded-md transition-colors"
          >
            1
          </Link>
        )}
      </li>
    );

    // 左侧省略号
    if (currentPage > 3) {
      pageButtons.push(
        <li key="left-ellipsis" className="px-2 py-2 text-gray-400">
          ...
        </li>
      );
    }

    // 当前页码附近的页码
    for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
      if (i === 1 || i === totalPages) continue; // 避免和首页、尾页重复

      pageButtons.push(
        <li key={i}>
          {i === currentPage ? (
            <span className="px-4 py-2 bg-red-600 text-white rounded-md cursor-default">
              {i}
            </span>
          ) : (
            <Link
              href={createPageLink(i)}
              onClick={(e) => handlePageClick(i, e)}
              className="px-4 py-2 bg-gray-800 hover:bg-gray-700 text-white rounded-md transition-colors"
            >
              {i}
            </Link>
          )}
        </li>
      );
    }

    // 右侧省略号
    if (currentPage < totalPages - 2) {
      pageButtons.push(
        <li key="right-ellipsis" className="px-2 py-2 text-gray-400">
          ...
        </li>
      );
    }

    // 始终显示尾页按钮（如果总页数大于1）
    if (totalPages > 1) {
      pageButtons.push(
        <li key="last">
          {currentPage === totalPages ? (
            <span className="px-4 py-2 bg-red-600 text-white rounded-md cursor-default">
              {totalPages}
            </span>
          ) : (
            <Link
              href={createPageLink(totalPages)}
              onClick={(e) => handlePageClick(totalPages, e)}
              className="px-4 py-2 bg-gray-800 hover:bg-gray-700 text-white rounded-md transition-colors"
            >
              {totalPages}
            </Link>
          )}
        </li>
      );
    }

    return pageButtons;
  };

  return (
    <div className="mt-8 mb-4 flex items-center justify-center">
      {/* 移动端分页 - 在中屏(md)以下显示 */}
      <div className="md:hidden flex items-center justify-center w-full">
        <div className="flex space-x-2">
          {/* 上一页 */}
          {currentPage > 1 ? (
            <Link
              href={createPageLink(currentPage - 1)}
              onClick={(e) => handlePageClick(currentPage - 1, e)}
              className="px-4 py-2 bg-gray-800 text-white rounded-lg hover:bg-gray-700 transition-colors flex items-center"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-5 w-5 mr-1"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M15 19l-7-7 7-7"
                />
              </svg>
              上一页
            </Link>
          ) : (
            <span className="px-4 py-2 bg-gray-900 text-gray-500 rounded-lg cursor-not-allowed flex items-center">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-5 w-5 mr-1"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M15 19l-7-7 7-7"
                />
              </svg>
              上一页
            </span>
          )}

          {/* 页码指示器 */}
          <span className="px-4 py-2 bg-gray-800 text-white rounded-lg">
            {currentPage} / {totalPages}
          </span>

          {/* 下一页 */}
          {currentPage < totalPages ? (
            <Link
              href={createPageLink(currentPage + 1)}
              onClick={(e) => handlePageClick(currentPage + 1, e)}
              className="px-4 py-2 bg-gray-800 text-white rounded-lg hover:bg-gray-700 transition-colors flex items-center"
            >
              下一页
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-5 w-5 ml-1"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M9 5l7 7-7 7"
                />
              </svg>
            </Link>
          ) : (
            <span className="px-4 py-2 bg-gray-900 text-gray-500 rounded-lg cursor-not-allowed flex items-center">
              下一页
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-5 w-5 ml-1"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M9 5l7 7-7 7"
                />
              </svg>
            </span>
          )}
        </div>
      </div>

      {/* 桌面端分页 - 在中屏(md)及以上显示 */}
      <nav className="hidden md:flex items-center space-x-1">
        {/* 上一页按钮 */}
        {currentPage > 1 ? (
          <Link
            href={createPageLink(currentPage - 1)}
            onClick={(e) => handlePageClick(currentPage - 1, e)}
            className="px-3 py-2 bg-gray-800 text-white rounded-md hover:bg-gray-700 transition-colors mr-2"
            aria-label="上一页"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-5 w-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M15 19l-7-7 7-7"
              />
            </svg>
          </Link>
        ) : (
          <span
            className="px-3 py-2 bg-gray-900 text-gray-500 rounded-md cursor-not-allowed mr-2"
            aria-label="上一页（禁用）"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-5 w-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M15 19l-7-7 7-7"
              />
            </svg>
          </span>
        )}

        {/* 页码按钮 */}
        <ul className="flex items-center space-x-1">
          {renderPageButtons()}
        </ul>

        {/* 下一页按钮 */}
        {currentPage < totalPages ? (
          <Link
            href={createPageLink(currentPage + 1)}
            onClick={(e) => handlePageClick(currentPage + 1, e)}
            className="px-3 py-2 bg-gray-800 text-white rounded-md hover:bg-gray-700 transition-colors ml-2"
            aria-label="下一页"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-5 w-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M9 5l7 7-7 7"
              />
            </svg>
          </Link>
        ) : (
          <span
            className="px-3 py-2 bg-gray-900 text-gray-500 rounded-md cursor-not-allowed ml-2"
            aria-label="下一页（禁用）"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-5 w-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M9 5l7 7-7 7"
              />
            </svg>
          </span>
        )}
      </nav>
    </div>
  );
} 